% (1+1)-ES Slide 61
% Michael Sieber, Philipp Rusch

function ex2a()
%initialization (line 1)
N = 10;
parent = 10 .* ones(N, 1)'; % all vector values are 10 (example from slide 71)
sigma = 1;

% determine initial parent fitness (line 2)
parent_fitness = F(parent);

% generation counter (line 3)
g = 0;

% generation and fitness log for plotting
plot_generations(g+1) = [g];
plot_fitness(g+1) = [parent_fitness];

% evolution loop (line 4)
while(g < 2000)
	% calculate offsprings (line 5-6)
	offspring = parent + sigma * randn(N, 1)';
	offspring_fitness = F(offspring);
	
	% minimization (line 7-10)
	if(offspring_fitness <= parent_fitness)
		parent = offspring;
		parent_fitness = offspring_fitness;
	endif
	
	% generation increase (line 11)
	g = g+1;
	
	% add the plot values
	plot_generations(g) = [g];
	plot_fitness(g) = [parent_fitness];
endwhile

printf("%s: %d\n", "Generations", g);
printf("%s: %f\n", "Parental fitness", parent_fitness);

% print the result
clf();
disp("y:"); disp(parent);
semilogy(plot_generations, plot_fitness);
ylabel("Parental Fitness F(y)");
xlabel("Generations");
axis([0, 2000, 0.1, 1000]); %[xmin, xmax, ymin, ymax]
endfunction